package com.powernobug.util;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Map;

/**
 * @description:
 * @project: project1-no-bug
 * @package: com.powernobug.util
 * @author: HuangWeiLong
 * @date: 2024/8/27 22:23
 */
public class BeanUtil {
    // Converter → 有参构造方法的形参 提供的是转换过程中的默认值
static {
        // Converter → 有参构造方法的形参 提供的是转换过程中的默认值
        DateConverter converter = new DateConverter(null);
        // 将字符串转换为Date的使用 采用的pattern(格式)
        converter.setPatterns(new String[]{"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss"});
        ConvertUtils.register(converter, Date.class);
    }
    public static <T> T queryParamPagemant(Class<T> instance,HttpServletRequest req){
        Map<String, String[]> parameterMap = req.getParameterMap();
        T newInstance = null;
        try {
            Constructor<T> constructor = instance.getConstructor();
            newInstance = constructor.newInstance();
            BeanUtils.copyProperties(newInstance, parameterMap);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        return newInstance;
    }
}
